package com.example.wx.dailyreport.controller.security.filter;


import com.example.wx.dailyreport.customtool.JWTTool;
import com.example.wx.dailyreport.customtool.JsonTool;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;

    public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
        super.setFilterProcessesUrl("/login");
    }


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password))
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        throw new BadCredentialsException("参数错误");
    }

    // 成功验证后调用的方法
    // 如果验证成功，就生成token并返回
    @Override
    protected void successfulAuthentication(HttpServletRequest request,
                                            HttpServletResponse response,
                                            FilterChain chain,
                                            Authentication authentication) throws IOException, ServletException {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put(JWTTool.JWT_USERNAME, authentication.getPrincipal());
        map.put(JWTTool.JWT_ROLE, new LinkedList<>(authentication.getAuthorities()).getFirst().toString());
        String token = JWTTool.createJwt(map);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setHeader(JWTTool.TOKEN_HEADER, JWTTool.TOKEN_PREFIX + token);
        Map<String, Object> resmap = new LinkedHashMap<>();
        resmap.put("status", 200);
        response.getWriter().write(JsonTool.toJson(resmap));
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        response.setContentType("application/json; charset=utf-8");
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("status", 400);
        map.put("message", failed.getMessage());
        response.getWriter().write(JsonTool.toJson(map));
    }

}
